package com.example.demo.study.thread;

import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * Thread Safety
 *
 */
public class ThreadSafety {
    //method1:
    //safety
    //public static final List<Integer> list=Collections.synchronizedList(new ArrayList<>());
    //not safety
    public static final List<Integer> list=new ArrayList<>();
    public static final Object lock=new Object();
    public   static void add(List<Integer> list)
    {
        //method2:
        synchronized (lock)
        {
            for (int i = 0; i < 1000; i++) {
                list.add(10);
            }
        }

    }
    public static void main(String[] args) throws InterruptedException {
        ExecutorService executor= Executors.newFixedThreadPool(3);
        List<Runnable> l=new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            l.add( ()->add(list) );
        }
        for(Runnable r:l)
        {
           executor.submit(r);
        }

        executor.shutdown();
        try {
            // 等待所有任务完成，最多等待10秒
            if (!executor.awaitTermination(10, TimeUnit.SECONDS)) {
                // 超时后强制关闭
                executor.shutdownNow();
            }
        } catch (InterruptedException e) {
            // 如果当前线程被中断，则强制关闭
            executor.shutdownNow();
        }
        System.out.println("All tasks have been completed or terminated.");
        System.out.println(list.size());
    }
}
